package com.example.logindemo.repository;

import com.example.logindemo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
    // 根据用户名查找用户
    Optional<User> findByUsername(String username);
    
    // 检查用户名是否已存在
    boolean existsByUsername(String username);
    
    // 根据邮箱查找用户
    boolean existsByEmail(String email);
    
    // 使用JOIN FETCH加载用户的角色信息
    @Query("SELECT u FROM User u JOIN FETCH u.roles WHERE u.username = :username")
    Optional<User> findByUsernameWithRoles(@Param("username") String username);
    
    // 使用JOIN FETCH加载用户的角色和权限信息
    @Query("SELECT u FROM User u JOIN FETCH u.roles r JOIN FETCH r.permissions WHERE u.username = :username")
    Optional<User> findByUsernameWithRolesAndPermissions(@Param("username") String username);
}